#!/bin/bash

# Property Cleaning System - Remote Anolis 7.9 Server One-Click Deployment Script
# Server Information: 10.158.94.94
# Deployment User: gs
# Deployment Time: $(date '+%Y-%m-%d %H:%M:%S')

set -e

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Property Cleaning System - Remote Deployment${NC}"
echo -e "${GREEN}  Server: 10.158.94.94${NC}"
echo -e "${GREEN}  User: gs${NC}"
echo -e "${GREEN}========================================${NC}"

# Check for root or sudo privileges
if [[ $EUID -ne 0 ]]; then
    echo -e "${YELLOW}Note: Running with sudo privileges${NC}"
    SUDO_CMD="sudo"
else
    SUDO_CMD=""
fi

# Configuration variables
DB_NAME="property_cleaning"
DB_ROOT_PASSWORD="root123"
DB_USER="property_user"
DB_PASSWORD="property_pass"
DB_PORT="3306"
BACKEND_PORT="8080"
FRONTEND_PORT="3000"

# Create project directory
echo -e "${BLUE}[1/8] Creating project directory...${NC}"
$SUDO_CMD mkdir -p /opt/property-cleaning-system/{database,backend,frontend,logs}
$SUDO_CMD chown -R gs:gs /opt/property-cleaning-system

# Update system
echo -e "${BLUE}[2/8] Updating system packages...${NC}"
$SUDO_CMD yum update -y
$SUDO_CMD yum install -y epel-release wget curl vim net-tools mysql-server mysql

# Start MySQL service
echo -e "${BLUE}[3/8] Configuring MySQL database...${NC}"
$SUDO_CMD systemctl start mysqld
$SUDO_CMD systemctl enable mysqld

# Wait for MySQL to start
sleep 5

# Set MySQL root password
mysql -u root << EOF
ALTER USER 'root'@'localhost' IDENTIFIED BY '${DB_ROOT_PASSWORD}';
CREATE DATABASE IF NOT EXISTS ${DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${DB_USER}'@'%' IDENTIFIED BY '${DB_PASSWORD}';
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'%';
FLUSH PRIVILEGES;
EOF

# Create database schema
echo -e "${BLUE}[4/8] Importing database structure...${NC}"
cat > /opt/property-cleaning-system/database/schema.sql << 'EOF'
-- Property Cleaning System Database Design
-- MySQL 8.0+ Compatible

USE property_cleaning;

-- Users table
CREATE TABLE IF NOT EXISTS users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'User ID',
    username VARCHAR(50) NOT NULL UNIQUE COMMENT 'Username',
    password VARCHAR(255) NOT NULL COMMENT 'Password (encrypted)',
    real_name VARCHAR(50) NOT NULL COMMENT 'Real name',
    email VARCHAR(100) UNIQUE COMMENT 'Email',
    phone VARCHAR(20) COMMENT 'Phone number',
    avatar_url VARCHAR(255) COMMENT 'Avatar URL',
    status TINYINT DEFAULT 1 COMMENT 'Status: 1 active 0 disabled',
    role ENUM('ADMIN', 'MANAGER', 'CLEANER', 'USER') DEFAULT 'USER',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Areas table
CREATE TABLE IF NOT EXISTS areas (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Area ID',
    area_name VARCHAR(100) NOT NULL COMMENT 'Area name',
    area_code VARCHAR(50) NOT NULL UNIQUE COMMENT 'Area code',
    parent_id BIGINT DEFAULT 0 COMMENT 'Parent area ID',
    area_type ENUM('BUILDING', 'FLOOR', 'PUBLIC') NOT NULL COMMENT 'Area type',
    description TEXT COMMENT 'Area description',
    status TINYINT DEFAULT 1 COMMENT 'Status: 1 enabled 0 disabled',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Cleaners table
CREATE TABLE IF NOT EXISTS cleaners (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Cleaner ID',
    user_id BIGINT NOT NULL COMMENT 'Associated user ID',
    employee_no VARCHAR(50) NOT NULL UNIQUE COMMENT 'Employee number',
    skill_level ENUM('JUNIOR', 'MIDDLE', 'SENIOR') DEFAULT 'JUNIOR',
    work_experience INT DEFAULT 0 COMMENT 'Work experience (years)',
    specialties TEXT COMMENT 'Professional skills',
    hire_date DATE COMMENT 'Hire date',
    status TINYINT DEFAULT 1 COMMENT 'Status: 1 on duty 2 on leave 3 resigned',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

-- Cleaning tasks table
CREATE TABLE IF NOT EXISTS cleaning_tasks (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Task ID',
    task_code VARCHAR(50) NOT NULL UNIQUE COMMENT 'Task code',
    task_name VARCHAR(200) NOT NULL COMMENT 'Task name',
    area_id BIGINT NOT NULL COMMENT 'Area ID',
    assigned_cleaner BIGINT COMMENT 'Assigned cleaner',
    task_date DATE NOT NULL COMMENT 'Task date',
    start_time TIME COMMENT 'Start time',
    end_time TIME COMMENT 'End time',
    task_status ENUM('PENDING', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED') DEFAULT 'PENDING',
    priority ENUM('LOW', 'MEDIUM', 'HIGH', 'URGENT') DEFAULT 'MEDIUM',
    description TEXT COMMENT 'Task description',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (area_id) REFERENCES areas(id),
    FOREIGN KEY (assigned_cleaner) REFERENCES cleaners(id)
);

-- Equipment table
CREATE TABLE IF NOT EXISTS equipment (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Equipment ID',
    equipment_name VARCHAR(100) NOT NULL COMMENT 'Equipment name',
    equipment_code VARCHAR(50) NOT NULL UNIQUE COMMENT 'Equipment code',
    equipment_type ENUM('CLEANING', 'SECURITY', 'OTHER') NOT NULL,
    model VARCHAR(100) COMMENT 'Equipment model',
    purchase_date DATE COMMENT 'Purchase date',
    status ENUM('NORMAL', 'MAINTENANCE', 'SCRAP') DEFAULT 'NORMAL',
    location VARCHAR(200) COMMENT 'Storage location',
    description TEXT COMMENT 'Equipment description',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Supplies table
CREATE TABLE IF NOT EXISTS supplies (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Supply ID',
    supply_name VARCHAR(100) NOT NULL COMMENT 'Supply name',
    supply_code VARCHAR(50) NOT NULL UNIQUE COMMENT 'Supply code',
    specification VARCHAR(200) COMMENT 'Specification model',
    unit VARCHAR(20) NOT NULL COMMENT 'Unit of measurement',
    stock_quantity INT DEFAULT 0 COMMENT 'Stock quantity',
    min_stock INT DEFAULT 10 COMMENT 'Minimum stock warning',
    unit_price DECIMAL(10,2) COMMENT 'Unit price',
    description TEXT COMMENT 'Supply description',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Owner feedback table
CREATE TABLE IF NOT EXISTS owner_feedback (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Feedback ID',
    feedback_code VARCHAR(50) NOT NULL UNIQUE COMMENT 'Feedback code',
    owner_name VARCHAR(50) NOT NULL COMMENT 'Owner name',
    owner_contact VARCHAR(50) NOT NULL COMMENT 'Owner contact',
    room_number VARCHAR(50) COMMENT 'Room number',
    feedback_type ENUM('COMPLIMENT', 'COMPLAINT', 'SUGGESTION', 'REPAIR') NOT NULL,
    feedback_content TEXT NOT NULL COMMENT 'Feedback content',
    status ENUM('PENDING', 'PROCESSING', 'COMPLETED', 'CLOSED') DEFAULT 'PENDING',
    handler_id BIGINT COMMENT 'Handler ID',
    handle_result TEXT COMMENT 'Handle result',
    satisfaction TINYINT COMMENT 'Satisfaction: 1-5 stars',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Insert initial data
INSERT INTO users (username, password, real_name, email, phone, role, status) VALUES
('admin', '$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBaUKk7h.T0mJ2', 'System Administrator', 'admin@property.com', '13800138000', 'ADMIN', 1),
('manager1', '$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBaUKk7h.T0mJ2', 'Property Manager', 'manager@property.com', '13800138001', 'MANAGER', 1),
('cleaner1', '$2a$10$N.zmdr9k7uOCQb376NoUnuTJ8iAt6Z5EHsM8lE9lBaUKk7h.T0mJ2', 'Zhang Cleaner', 'cleaner1@property.com', '13800138002', 'CLEANER', 1);

INSERT INTO areas (area_name, area_code, area_type, description, status) VALUES
('Building A', 'A-BUILDING', 'BUILDING', 'Building A residential', 1),
('Building B', 'B-BUILDING', 'BUILDING', 'Building B residential', 1),
('Lobby Area', 'LOBBY-AREA', 'PUBLIC', 'First floor lobby public area', 1),
('Underground Parking', 'PARKING-AREA', 'PUBLIC', 'Underground parking area', 1);

INSERT INTO cleaners (user_id, employee_no, skill_level, work_experience, hire_date, status) VALUES
(3, 'EMP001', 'MIDDLE', 3, '2023-01-15', 1);

INSERT INTO equipment (equipment_name, equipment_code, equipment_type, model, location, status) VALUES
('Floor Scrubber', 'EQ001', 'CLEANING', 'KARCHER-BD50', 'Equipment Warehouse', 'NORMAL'),
('Vacuum Cleaner', 'EQ002', 'CLEANING', 'PHILIPS-FC8088', 'Equipment Warehouse', 'NORMAL');

INSERT INTO supplies (supply_name, supply_code, specification, unit, stock_quantity, unit_price) VALUES
('Disinfectant', 'SUP001', '500ml/bottle', 'bottle', 100, 15.50),
('Garbage Bags', 'SUP002', 'Large black', 'piece', 500, 0.50),
('Cleaning Cloths', 'SUP003', 'Microfiber', 'piece', 50, 8.00);

EOF

# Configure firewall
echo -e "${BLUE}[5/8] Configuring firewall...${NC}"
$SUDO_CMD firewall-cmd --permanent --add-port=${DB_PORT}/tcp
$SUDO_CMD firewall-cmd --permanent --add-port=${BACKEND_PORT}/tcp
$SUDO_CMD firewall-cmd --permanent --add-port=${FRONTEND_PORT}/tcp
$SUDO_CMD firewall-cmd --reload

# Create Spring Boot configuration file
echo -e "${BLUE}[6/8] Creating application configuration...${NC}"
cat > /opt/property-cleaning-system/application-prod.yml << EOF
server:
  port: ${BACKEND_PORT}

spring:
  application:
    name: property-cleaning-system
  
  datasource:
    url: jdbc:mysql://localhost:${DB_PORT}/${DB_NAME}?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf8
    username: ${DB_USER}
    password: ${DB_PASSWORD}
    driver-class-name: com.mysql.cj.jdbc.Driver
  
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: false
    database-platform: org.hibernate.dialect.MySQL8Dialect

logging:
  level:
    com.property: INFO
  file:
    name: /opt/property-cleaning-system/logs/property-cleaning.log

management:
  endpoints:
    web:
      exposure:
        include: health,info
  endpoint:
    health:
      show-details: always
EOF

# Create startup script
echo -e "${BLUE}[7/8] Creating startup scripts...${NC}"
cat > /opt/property-cleaning-system/start-all.sh << 'EOF'
#!/bin/bash
echo "Starting Property Cleaning System..."

# Start MySQL
sudo systemctl start mysqld

# Wait for MySQL to start
sleep 3

# Start backend (requires Java environment)
if command -v java &> /dev/null; then
    cd /opt/property-cleaning-system/backend
    nohup java -jar -Dspring.profiles.active=prod property-cleaning.jar > ../logs/backend.log 2>&1 &
    echo "Backend service started"
else
    echo "Warning: Java environment not found, backend service needs manual start"
fi

# Start frontend (requires Node.js environment)
if command -v node &> /dev/null; then
    cd /opt/property-cleaning-system/frontend
    nohup python3 -m http.server 3000 > ../logs/frontend.log 2>&1 &
    echo "Frontend service started"
else
    echo "Warning: Using Python HTTP server for frontend"
    cd /opt/property-cleaning-system/frontend
    nohup python3 -m http.server 3000 > ../logs/frontend.log 2>&1 &
fi

echo "System startup complete!"
echo "Access URLs:"
echo "- Frontend: http://10.158.94.94:3000"
echo "- Backend API: http://10.158.94.94:8080"
echo "- API Documentation: http://10.158.94.94:8080/swagger-ui.html"
EOF

chmod +x /opt/property-cleaning-system/start-all.sh

# Create status check script
cat > /opt/property-cleaning-system/check-status.sh << 'EOF'
#!/bin/bash
echo "System Status Check:"
echo "=================="
echo "MySQL Status:"
sudo systemctl status mysqld --no-pager -l

echo
echo "Port Listening Status:"
netstat -tlnp | grep -E ':(3000|8080|3306)'

echo
echo "Service Health Check:"
curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 | grep -q "200" && echo "✅ Frontend service normal" || echo "❌ Frontend service abnormal"
curl -s -o /dev/null -w "%{http_code}" http://localhost:8080 | grep -q "200" && echo "✅ Backend service normal" || echo "❌ Backend service abnormal"

echo
echo "Database Connection Test:"
mysql -u${DB_USER} -p${DB_PASSWORD} -e "SELECT 'Database connection successful' AS status;" ${DB_NAME} 2>/dev/null && echo "✅ Database connection successful" || echo "❌ Database connection failed"
EOF

chmod +x /opt/property-cleaning-system/check-status.sh

# Create backup script
cat > /opt/property-cleaning-system/backup-db.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/opt/property-cleaning-system/backups"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

echo "Starting database backup..."
mysqldump -u${DB_USER} -p${DB_PASSWORD} ${DB_NAME} > $BACKUP_DIR/property_cleaning_backup_$DATE.sql

echo "Backup completed: $BACKUP_DIR/property_cleaning_backup_$DATE.sql"
EOF

chmod +x /opt/property-cleaning-system/backup-db.sh

# Set up scheduled tasks
echo "0 2 * * * /opt/property-cleaning-system/backup-db.sh" | crontab -

echo -e "${GREEN}[8/8] Deployment completed!${NC}"
echo
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  Property Cleaning System deployment successful!${NC}"
echo -e "${GREEN}========================================${NC}"
echo
echo -e "${BLUE}Project directory:${NC} /opt/property-cleaning-system"
echo -e "${BLUE}Database configuration:${NC}"
echo -e "  Host: 10.158.94.94"
echo -e "  Port: ${DB_PORT}"
echo -e "  Database: ${DB_NAME}"
echo -e "  User: ${DB_USER}"
echo -e "  Password: ${DB_PASSWORD}"
echo
echo -e "${BLUE}Access URLs:${NC}"
echo -e "  Frontend: http://10.158.94.94:${FRONTEND_PORT}"
echo -e "  Backend API: http://10.158.94.94:${BACKEND_PORT}"
echo -e "  API Documentation: http://10.158.94.94:${BACKEND_PORT}/swagger-ui.html"
echo
echo -e "${BLUE}Management commands:${NC}"
echo -e "  Start system: /opt/property-cleaning-system/start-all.sh"
echo -e "  Check status: /opt/property-cleaning-system/check-status.sh"
echo -e "  Backup data: /opt/property-cleaning-system/backup-db.sh"
echo
echo -e "${GREEN}System is ready!${NC}"